from django.shortcuts import render, get_object_or_404
from models import Post, Comment
from forms import CommentForm

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from markdown import markdown

# Create your views here.

# change this to False and there will be no comment section
COMMENTS_ALLOWED = True

def index(request):
    '''
    List all blog posts.
    '''

    post_list = Post.objects.all().order_by('last_edited').reverse()

    context = {
        'title': "Welcome",
        'post_list': post_list,
    }

    return render(request, 'index.html', context)

def detail(request, token):
    '''
    View a single blog post by its ID or post a comment if request is POST.

    token should be an integer.
    '''


    if request.method == "POST": # no GET allowed.
        p = get_object_or_404(Post, id=token)
        
        form = CommentForm(request.POST)
        if form.is_valid():
            # look around cleaned_data
            c = Comment(
                author=form.cleaned_data['author'],
                website=form.cleaned_data['website'],
                content=form.cleaned_data['content'],
                post=p,
            )
            c.save()
            return HttpResponseRedirect(reverse('detail', args=(token)))
        else:
            context = {
                'title': post.title,
                'post': post,
                'content': content,
                'comments': comments,
                'commenting': COMMENTS_ALLOWED,
                'form': form,
                'error': "There were errors filling out the form.",
            }
            return render(request, 'detail.html', context)

    else: # GET
        post = get_object_or_404(Post,id=token)
        comments = Comment.objects.filter(post__id=token)
        content = markdown(post.content)
        form = CommentForm()

        context = {
            'title': post.title,
            'post': post,
            'content': content,
            'comments': comments,
            'commenting': COMMENTS_ALLOWED,
            'form': form,
        }

        return render(request, 'detail.html', context)
